package org.tlang.ast.list.func;

import org.tlang.ast.AST;
import org.tlang.ast.ASTList;
import org.tlang.context.TypeTable;
import org.tlang.context.ValueTable;
import org.tlang.exception.TypeException;
import org.tlang.metaclass.TGetter;
import org.tlang.metaclass.TVar;
import org.tlang.type.Type;
import org.tlang.type.VoidType;

import java.util.List;

/**
 * 实参列表
 */
public class ArgumentList extends ASTList {
    private Type[] types;

    public ArgumentList(List<AST> children) {
        super(children);
    }

    public int size() {
        return numChildren();
    }

    /**
     * 实参需要在调用者环境中计算，结果更新函数局部环境对应的形参
     */
    public void eval(ValueTable localValueTable, ValueTable callerValueTable, int[] offsets) {
        for (int i = 0; i < offsets.length; i++) {
            Object value = child(i).eval(callerValueTable);
            if (value instanceof TGetter) {
                value = ((TGetter) value).get();
            }
            localValueTable.update(0, offsets[i], new TVar(value));
        }
    }

     public Type[] types() {
        return types;
    }

    @Override
    public Type typeCheck(TypeTable typeTable) throws TypeException {
        this.types = new Type[size()];
        for (int i = 0; i < size(); i++) {
            this.types[i] = child(i).typeCheck(typeTable);
        }
        return VoidType.VOID_TYPE;
    }

    @Override
    protected String toStringSep() {
        return ", ";
    }
}
